from django.conf.urls.defaults import *
from django.contrib import admin
from django.contrib.gis.geos import fromstr
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from geopy import geocoders
from reviews.forms import BulkAddPlacesForm
from reviews.models import Place, Dish, PlaceImage, DishImage
from sorting.models import List, ListMembership, Sorting, Item, SortDelta
from tagging.models import Tag, Tag_Relation


class ImageAdmin(admin.ModelAdmin):
    list_display = ('admin_thumbnail_view',)

class PlaceAdmin(admin.ModelAdmin):

    def get_urls(self):
        ''' Adding bulk upload view to admin site. '''
        urls = super(PlaceAdmin, self).get_urls()
        my_urls = patterns('',
            (r'^add/bulk$', self.admin_site.admin_view(self.bulk_add_view))
        )
        return my_urls + urls

    def bulk_add_view(self, request):
        if request.method == 'POST':
            form = BulkAddPlacesForm(request.POST, request.FILES)
            if form.is_valid():
                self.parse(request.FILES['file'])
                return HttpResponseRedirect('/admin/reviews/place')
        else:
            form = BulkAddPlacesForm()
        return render_to_response('reviews/bulkadd.html', {'form': form, 'current_app': self.admin_site.name},
                                  context_instance=RequestContext(request))

    def parse(self, f):
        g = geocoders.Google(resource='maps')
        ids = {}
        errors = []
        curr_id = ''
        i = 0 # keep track of field count since we expect 15 fields to be parsed from each line
        addr = ''
        trunc = ''
        counter = 0
        c = f.read();
        #for chunk in f.chunks():
            #c = str(chunk)
        while c: # do while c not empty
            a,b,c = c.partition(',')
		    # if contains newline, partition at newline           
            if a.find('\n') > -1:
                a,b2,c2 = a.partition('\n')
                c = c2 + ',' + c
            a = a.strip('"')
            a = a.strip(' ')
            if i is 0:
                if a in ids:
                    _,_,c = c.partition('\n')
                    continue # skip
                else:
                    ids[a] = 1
                    curr_id = a
            elif i is 1: # name
                name = a
            elif i is 3: # building #
                addr = a
            elif i is 4: # street
                addr = addr + ' ' + a
            elif i is 5: # zipcode
                addr = addr + ' ' + a
                # geopy lookup
                # print addr
                try:
                    place = addr
                    lat, lng = 0, 0
                    #place,(lat,lng) = g.geocode(addr)
                    addr = ''
                except:
                    place = addr
                    lat, lng = 0, 0
                    errors.append(curr_id)
            elif i is 6: # phone #
                phone_num = a
            elif i is 7: # cuisine code
                cuisine_code = i
            elif i is 14: # start over
                print phone_num
                place = Place(name=name, cuisine_code=cuisine_code, geometry=fromstr('POINT('+str(lat)+' '+str(lng)+')',srid=4326), phone_number = phone_num)
                place.save()
                print str(counter) + name
                counter = counter + 1
                # print 'Created ' + name
                # print 'i: ' + str(i)
                # print 'a: ' + a
                # print 'b: ' + b
                # print 'c: ' + c
                i = -1
            # print i
            i = i + 1
            # if not c and i > 0:
                # trunc = 
        print 'ERRORS: ' + errors

class TagsInline(admin.TabularInline):
    model = Dish.tags.through
    extra = 1


class ImageInline(admin.TabularInline):
    model = DishImage
    extra = 1

class ItemInline(admin.StackedInline):
    model = Item
    extra = 1


class DishAdmin(admin.ModelAdmin):
    list_display = ('name', 'place')
    inlines = [
        TagsInline,
        ImageInline,
        ItemInline,
    ]
    exclude = ('tags',)

class TagAdmin(admin.ModelAdmin):
    inlines = [
        TagsInline,
    ]



admin.site.register(Place, PlaceAdmin)
admin.site.register(Dish, DishAdmin)

admin.site.register(PlaceImage, ImageAdmin)
admin.site.register(DishImage, ImageAdmin)

admin.site.register(Tag, TagAdmin)
admin.site.register(Tag_Relation)